package com.gym.core.threadpool;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author xinchun.wang
 * @email: 532002108@qq.com
 * @createTime 2015-6-7 下午4:12:21
 */
public class TaskUtil {

	private static Logger logger = LoggerFactory.getLogger(TaskUtil.class.getName());

	private static ScheduledExecutorService service = Executors.newScheduledThreadPool(8);

	private static void close() {
		try {
			service.shutdown();
		} catch (Exception e) {
			try {
				service.shutdownNow();
			} catch (Exception e1) {
				logger.error(e1.getMessage(), e1);
			}
		}
	}

	public static void registerTaskJustOneInvoke(Runnable task, long delay, TimeUnit unit) {
		service.schedule(task, delay, unit);
		logger.info("注册任务:{} 成功", new Object[] {});
	}

	public static void registerTaskAtFixedRate(Runnable task, long initialDelay, long period, TimeUnit unit) {
		service.scheduleAtFixedRate(task, initialDelay, period, unit);
		logger.info("注册任务:{} 成功", new Object[] {});
	}

	static {
		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				close();
			}
		});
	}
}
